package cn.uncode.baas.server.internal.validator;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import cn.uncode.baas.server.constant.Resource;
import cn.uncode.baas.server.dto.RestField;
import cn.uncode.baas.server.exception.ValidateException;
import cn.uncode.baas.server.internal.RequestMap;
import cn.uncode.baas.server.internal.message.Messages;
import cn.uncode.baas.server.utils.WatchUtils;

public class ValidatorExecuter {

	private static final Logger LOG = Logger.getLogger(ValidatorExecuter.class);

	public static RequestMap<String, Object> validate(int type, List<RestField> restFields, RequestMap<String, Object> params)
	        throws ValidateException {
		RequestMap<String, Object> paramsMap = new RequestMap<String, Object>();
		if (Resource.REST_METHOD_PARAM_TYPE_ANY == type) {
			if (restFields != null) {
				WatchUtils.lap("validate start");
				for (RestField field : restFields) {
					checkParams(params, field);
				}
				WatchUtils.lap("validate end");
			}
			return params;
		} else if (Resource.REST_METHOD_PARAM_TYPE_CUSTOM == type) {
			if (restFields != null) {
				WatchUtils.lap("validate start");
				for (RestField field : restFields) {
					String value = checkParams(params, field);
					paramsMap.put(field.getFieldName(), value);
				}
				WatchUtils.lap("validate end");
			}
			return paramsMap;
		} else if (Resource.REST_METHOD_PARAM_TYPE_NOTHING == type) {
			//
		}
		return paramsMap;
	}

	/**
	 * 
	 * @param params
	 * @param field
	 * @return
	 */
	private static String checkParams(Map<String, Object> params, RestField field) {
		String value = String.valueOf(params.get(field.getFieldName()));
		if (LOG.isDebugEnabled()) {
			if (StringUtils.isEmpty(value)) {
				LOG.debug(Messages.getString("trace.1", field.getFieldName(), "null"));
			} else {
				LOG.debug(Messages.getString("trace.1", field.getFieldName(), value));
			}
		}
		if (field.isRequest() && StringUtils.isEmpty(value)) {
			throw new ValidateException(Messages.getString("ValidateError.1", field.getFieldName()));
		}
		if (StringUtils.isNotEmpty(value) && StringUtils.isNotEmpty(field.getRegular())) {
			Pattern p = Pattern.compile(field.getRegular());
			Matcher m = p.matcher(value);
			if (false == m.matches()) {
				throw new ValidateException(Messages.getString("ValidateError.3", field.getFieldName(), value,
				        field.getRegular()));
			}
		}
		return value;
	}

}
